const { Sequelize } = require('sequelize');
require('dotenv').config();

// 数据库配置
const dbConfig = {
  host: process.env.DB_HOST || '127.0.0.1',
  port: process.env.DB_PORT || 3306,
  username: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || 'zxy123',
  database: process.env.DB_NAME || 'nuxt3',
  dialect: 'mysql',
  logging: process.env.NODE_ENV === 'development' ? console.log : false,
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },
  define: {
    timestamps: true,
    underscored: true,
    freezeTableName: true
  }
};

// 创建Sequelize实例
const sequelize = new Sequelize(
  dbConfig.database,
  dbConfig.username,
  dbConfig.password,
  {
    host: dbConfig.host,
    port: dbConfig.port,
    dialect: dbConfig.dialect,
    logging: dbConfig.logging,
    pool: dbConfig.pool,
    define: dbConfig.define
  }
);

// 测试数据库连接
const testConnection = async () => {
  try {
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功');
    return true;
  } catch (error) {
    console.error('❌ 数据库连接失败:', error.message);
    return false;
  }
};

// 同步数据库模型
const syncDatabase = async (force = true) => {
  try {
    await sequelize.sync({ force });
    console.log('✅ 数据库同步完成');
    return true;
  } catch (error) {
    console.error('❌ 数据库同步失败:', error.message);
    return false;
  }
};

// 自动初始化数据库
const autoInitDatabase = async () => {
  try {
    console.log('🔌 正在连接数据库...');
    console.log(`📍 数据库地址: ${dbConfig.host}:${dbConfig.port}`);
    console.log(`🗄️  数据库名称: ${dbConfig.database}`);
    
    // 测试连接
    const isConnected = await testConnection();
    if (!isConnected) {
      console.error('❌ 无法连接到数据库，请检查MySQL服务是否启动');
      return false;
    }
    
    // 同步数据库结构
    console.log('📋 正在同步数据库表结构...');
    const syncResult = await syncDatabase(false); // 不强制重建，保留现有数据
    if (!syncResult) {
      return false;
    }
    
    console.log('✅ 数据库自动初始化完成');
    return true;
  } catch (error) {
    console.error('❌ 数据库自动初始化失败:', error.message);
    return false;
  }
};

module.exports = {
  sequelize,
  testConnection,
  syncDatabase,
  autoInitDatabase,
  dbConfig
}; 